package com.zimi.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimi.mapper.SysOrgMapper;
import com.zimi.mapper.SysOrgPartnerMapper;
import com.zimi.model.SysOrg;
import com.zimi.model.SysOrgExtend;
import com.zimi.model.SysOrgPartner;
import com.zimi.model.SysUser;
import com.zimi.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 系统用户表 Service
 *
 * @author lxc
 * @since 2019-06-24
 */
@Service
public class SysOrgPartnerService {
    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Autowired
    private SysOrgPartnerMapper sysOrgPartnerMapper;

    /**
     * @param orgId
     * @return
     * @authot wh
     * @desc 根据orgId获取已关联的单位
     */
    public List<SysOrg> getPageList(int orgId) {
        List<SysOrg> result = new ArrayList<>();
        List<SysOrgPartner> list = sysOrgPartnerMapper.selectList(new LambdaQueryWrapper<SysOrgPartner>().eq(SysOrgPartner::getState, 1).eq(SysOrgPartner::getOrgId, orgId));

        if (list != null && list.size() > 0) {
            for (SysOrgPartner sop : list) {
                SysOrg org = new SysOrg().selectById(sop.getTargetOrgId()); //根据id获取机构名
                SysOrg tmpOrg = new SysOrg();

                tmpOrg.setId(sop.getId());
                tmpOrg.setOrgName(org.getOrgName());
                tmpOrg.setOgnId(sop.getTargetOrgId());
                tmpOrg.setOrgState(sop.getState());
                tmpOrg.setUpdateTime(sop.getUpdateTime());

                result.add(tmpOrg);
            }
        }

        return result;
    }


    public List<SysOrgExtend> getPartnerOgnList(int orgId) {

        List idList = new ArrayList();

        // 1)取出机构根节点编号
        List<SysOrg> list = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getOrgState, 1).ne(SysOrg::getOgnId, orgId).eq(SysOrg::getOrgPid, 0).orderByAsc(SysOrg::getOrgSort));
        List<SysOrg> list1 = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getOrgPid, 0));

        for (SysOrg i : list1) {
            idList.add(i.getId());
        }

        if (!idList.contains(orgId)) {
            return null;
        }

        List<SysOrgExtend> sysOrgExtends = new ArrayList<>();
        SysOrgExtend tmpSysOrgExtend = null;

        if (list != null && list.size() > 0) {
            // 2）取出关系企业表一览
            List<SysOrgPartner> sysOrgPartners = sysOrgPartnerMapper.selectList(new QueryWrapper<SysOrgPartner>().lambda().eq(SysOrgPartner::getOrgId, orgId));
            Map<Integer, SysOrgPartner> sysOrgPartnerMap = new HashMap<>();

            if (sysOrgPartners != null & sysOrgPartners.size() > 0) {
                for (SysOrgPartner sop : sysOrgPartners) {
                    sysOrgPartnerMap.put(sop.getTargetOrgId(), sop);
                }
            }

            // 3）编辑返回值一览
            SysOrgPartner sysOrgPartner = null;
            for (SysOrg so : list) {
                tmpSysOrgExtend = new SysOrgExtend();

                tmpSysOrgExtend.setOrgId(so.getId());
                tmpSysOrgExtend.setOrgName(so.getOrgName());

                sysOrgPartner = sysOrgPartnerMap.get(tmpSysOrgExtend.getOrgId());
                if (sysOrgPartner != null) {
                    if (sysOrgPartner.getState() == 1) {
                        tmpSysOrgExtend.setChoiceFlag(true);
                    }
                    tmpSysOrgExtend.setId(sysOrgPartner.getId());
                    tmpSysOrgExtend.setUpdateTime(sysOrgPartner.getUpdateTime());
                }
                sysOrgExtends.add(tmpSysOrgExtend);
            }
        }

        return sysOrgExtends;
    }

    /**
     * @param orgId
     * @param orgList
     * @author wh
     * @desc 新增单位关联单位
     */
    @Transactional
    public void save(int orgId, List<SysOrg> orgList) {

        SysUser user = UserUtil.getUser();
        Date tmpTime = new Date();

        if (orgList != null && orgList.size() > 0) {
            for (SysOrg so : orgList) {
                SysOrgPartner tmpPartner = new SysOrgPartner();
                tmpPartner.setOrgId(orgId);
                tmpPartner.setTargetOrgId(so.getOgnId());
                tmpPartner.setState(1);

                if (so.getId() == null) { //1)根据id为null进行添加
                    tmpPartner.setCreateUser(user.getId());
                    tmpPartner.setCreateTime(tmpTime);

                    tmpPartner.insert();
                } else { //2）根据id不为null进行修改state为1

                    // 1）对要修改的对象加行锁
                    SysOrgPartner result = new SysOrgPartner().selectOne(new QueryWrapper<SysOrgPartner>().lambda().eq(SysOrgPartner::getId, so.getId()).last("for update"));

                    // 2）判断该数据已经被改过没有
                    if (result.getUpdateTime() != null) {
                        if (so.getUpdateTime() == null) {
                            throw new RuntimeException("修改数据失败，数据已经被其他用户改过。");
                        } else {
                            if (so.getUpdateTime().getTime() != result.getUpdateTime().getTime()) {
                                throw new RuntimeException("修改数据失败，数据已经被其他用户改过。");
                            }
                        }
                    }

                    tmpPartner.setId(so.getId());
                    tmpPartner.setUpdateUser(user.getId());
                    tmpPartner.setCreateTime(tmpTime);

                    tmpPartner.updateById();
                }
            }
        }
    }

    /**
     * @param partner
     * @authot wh
     * @desc 逻辑删除关联单位
     */
    @Transactional
    public void del(SysOrgPartner partner) {
        SysUser user = UserUtil.getUser();
        Date tmpTime = new Date();


        SysOrgPartner result = new SysOrgPartner().selectOne(new LambdaQueryWrapper<SysOrgPartner>().eq(SysOrgPartner::getId, partner.getId()).last("for update"));

        if (result.getUpdateTime() != null) {
            if (partner.getUpdateTime() == null) {
                throw new RuntimeException("修改数据失败，数据已经被其他用户改过。");
            } else {
                if (partner.getUpdateTime().getTime() != result.getUpdateTime().getTime()) {
                    throw new RuntimeException("修改数据失败，数据已经被其他用户改过。");
                }
            }
        }

        partner.setState(2);
        partner.setUpdateUser(user.getId());
        partner.setUpdateTime(tmpTime);

        partner.updateById();
    }

}
